#include "farminfowidget.h"
#include <QPixmap>

FarmInfoWidget::FarmInfoWidget(QWidget *parent,QString permission) : QWidget(parent), permission(permission),co2Value(0.0),
    tempValue(0.0),
    humidityValue(0.0),
    lightValue(0.0)
{
     clt=new MqttClient("120.26.201.192",1883,"guoren");
     clt->getConstantValue(farmId);
     connect(clt,&MqttClient::achievedConstantValue,[=](int farm_id, float co2, float temperature, float humidity, float light_intensity)
     {
         qDebug()<<"co2阈值                     "<<co2;
     });
    // clt->setConstantValue(1,1.2,30,20,1000);
        setupUI();
       // loadData();

        // 创建刷新定时器
        refreshTimer = new QTimer(this);
        refreshTimer->setInterval(1000); // 1秒刷新一次
        connect(refreshTimer, &QTimer::timeout, this, &FarmInfoWidget::loadData);
        refreshTimer->start();



}

void FarmInfoWidget::setupUI()
{

    //this->setStyleSheet("background-image: url(:/icon/farminfo.png);");

    // 创建主布局 - 使用垂直布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    // 标题
    QLabel *titleLabel = new QLabel("农场环境监测", this);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color: #2c6e49;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // 创建主内容布局 - 水平布局
    QHBoxLayout *contentLayout = new QHBoxLayout();
    contentLayout->setSpacing(15);
    contentLayout->setContentsMargins(0, 0, 0, 0);

    // === 左侧卡片区域 ===
    QVBoxLayout *leftCardLayout = new QVBoxLayout();
    leftCardLayout->setSpacing(15);
    leftCardLayout->setContentsMargins(0, 0, 0, 0);

    // CO2浓度卡片
    co2Card = new EnvCard("CO₂浓度", "ppm", this);
    connect(co2Card, &EnvCard::clicked, this, &FarmInfoWidget::onCo2Clicked);
    //co2Card->setFixedSize(180, 120);
    leftCardLayout->addWidget(co2Card);

    // 温度卡片
    tempCard = new EnvCard("温度", "°C", this);
    connect(tempCard, &EnvCard::clicked, this, &FarmInfoWidget::onTempClicked);
    //tempCard->setFixedSize(180, 120);
    leftCardLayout->addWidget(tempCard);

    // 添加左侧布局到主内容布局
    contentLayout->addLayout(leftCardLayout, 1); // 比例1

    // === 中间视频区域 ===
    QVBoxLayout *videoLayout = new QVBoxLayout();
    videoLayout->setSpacing(10);
    videoLayout->setContentsMargins(0, 0, 0, 0);

    // 创建视频播放器
    v = new VideoPlayer;
//    v->setVideo("1");
    v->setMinimumSize(600, 450); // 设置最小尺寸
    v->setStyleSheet("border: 1px solid #c8e6c9; border-radius: 8px;");
    videoLayout->addWidget(v, 0, Qt::AlignCenter);

    // 添加视频布局到主内容布局
    contentLayout->addLayout(videoLayout, 3); // 比例2，占据更多空间

    // === 右侧卡片区域 ===
    QVBoxLayout *rightCardLayout = new QVBoxLayout();
    rightCardLayout->setSpacing(15);
    rightCardLayout->setContentsMargins(0, 0, 0, 0);

    // 湿度卡片
    humidityCard = new EnvCard("湿度", "%", this);
    connect(humidityCard, &EnvCard::clicked, this, &FarmInfoWidget::onHumidityClicked);
  // humidityCard->setFixedSize(180, 120);
    rightCardLayout->addWidget(humidityCard);

    // 光照强度卡片
    lightCard = new EnvCard("光照强度", "lux", this);
    connect(lightCard, &EnvCard::clicked, this, &FarmInfoWidget::onLightClicked);
  // lightCard->setFixedSize(180, 120);
    rightCardLayout->addWidget(lightCard);

    // 添加右侧布局到主内容布局
    contentLayout->addLayout(rightCardLayout, 1); // 比例1

    // 添加主内容布局到主布局
    mainLayout->addLayout(contentLayout, 1); // 占据主要空间

    // 添加拉伸因子
    mainLayout->addStretch(1);

    // 设置布局
    setLayout(mainLayout);

    // 设置卡片是否可点击
    if(permission == "r") {
        bool shouldEnableClick = false;
        co2Card->setClickable(shouldEnableClick);
        tempCard->setClickable(shouldEnableClick);
        humidityCard->setClickable(shouldEnableClick);
        lightCard->setClickable(shouldEnableClick);
    }
}
void FarmInfoWidget::loadData()
{
    // 执行数据库查询
    QSqlQuery query;
    query.prepare("SELECT co2, temperature, humidity, light_intensity "
                  "FROM env_data "
                  "WHERE farm_id = ? "
                  "ORDER BY create_time DESC "
                  "LIMIT 1");
   // qDebug()<<farmId;
    query.addBindValue(farmId); // 假设农场ID为1

    if (!query.exec()) {
        QMessageBox::critical(this, "数据库错误",
                             "无法加载环境数据:\n" + query.lastError().text());
        return;
    }

    if (query.next()) {
        // 获取数据
        co2Value = query.value(0).toDouble();
        tempValue = query.value(1).toDouble();
        humidityValue = query.value(2).toDouble();
        lightValue = query.value(3).toDouble();

        // 更新显示
        updateDataDisplay();
       // co2Label->setText(QString::number(co2Value));
        // tempLabel->setText(QString::number(tempValue));

    } else {
        // 没有数据
        co2Card->setValueText("无数据");
                tempCard->setValueText("无数据");
                humidityCard->setValueText("无数据");
                lightCard->setValueText("无数据");
    }
}

void FarmInfoWidget::onPresetClicked()
{
    //qDebug()<<"nihao";
//    v=new VideoPlayer;
//    v->setVideo("1");
    v->show();
}

void FarmInfoWidget::updateDataDisplay()
{
    // 更新CO2显示
   co2Card->setValue(co2Value);

    // 根据CO2值设置颜色
   if (co2Value > 1000) {
          co2Card->setColor(QColor("#d32f2f")); // 红色
      } else {
          co2Card->setColor(QColor("#4b8a29")); // 绿色
      }

    // 更新温度显示
    tempCard->setValue(tempValue);
    // 根据温度值设置颜色
    if (tempValue < 10 || tempValue > 30) {
           tempCard->setColor(QColor("#d32f2f"));
       } else {
           tempCard->setColor(QColor("#4b8a29"));
       }

       // 更新湿度显示
       humidityCard->setValue(humidityValue);

       // 根据湿度值设置颜色
       if (humidityValue < 10 || humidityValue > 80) {
           humidityCard->setColor(QColor("#d32f2f"));
       } else {
           humidityCard->setColor(QColor("#4b8a29"));
       }

       // 更新光照强度显示
       lightCard->setValue(lightValue);

       // 根据光照强度设置颜色
       if (lightValue < 1000 || lightValue > 10000) {
           lightCard->setColor(QColor("#d32f2f"));
       } else {
           lightCard->setColor(QColor("#4b8a29"));
       }
}

void FarmInfoWidget::editValue(const QString &title, const QString &unit, double &value)
{

        // 创建编辑对话框
        QDialog dialog(this);
        dialog.setWindowTitle(title);
        dialog.setFixedSize(300, 150);

        // 创建主布局
        QVBoxLayout *mainLayout = new QVBoxLayout(&dialog);
        mainLayout->setSpacing(15);
        mainLayout->setContentsMargins(20, 20, 20, 20);

        // 创建表单布局
        QFormLayout *formLayout = new QFormLayout();
        formLayout->setSpacing(10);

        // 值输入框
        QLineEdit *valueEdit = new QLineEdit(&dialog);
        valueEdit->setText(QLocale().toString(value));
        valueEdit->setValidator(new QDoubleValidator(0, 100000, 2, this)); // 允许输入小数
        formLayout->addRow("值:", valueEdit);

        // 单位标签
        QLabel *unitLabel = new QLabel(unit, &dialog);
        unitLabel->setStyleSheet("font-size: 16px; color: #757575;");
        formLayout->addRow("单位:", unitLabel);

        mainLayout->addLayout(formLayout);

        // 按钮框
        QDialogButtonBox *buttonBox = new QDialogButtonBox(
            QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
        connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
        connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

        mainLayout->addWidget(buttonBox);

        // 设置样式
        dialog.setStyleSheet(
            "QDialog {"
            "  background-color: #f5fbf5;"
            "}"
            "QLabel {"
            "  font-weight: bold;"
            "  color: #2c6e49;"
            "}"
            "QLineEdit {"
            "  border: 1px solid #c8e6c9;"
            "  border-radius: 4px;"
            "  padding: 8px;"
            "  font-size: 16px;"
            "}"
            "QLineEdit:focus {"
            "  border: 1px solid #4b8a29;"
            "}"
            "QPushButton {"
            "  background-color: #4b8a29;"
            "  color: white;"
            "  min-width: 80px;"
            "  padding: 8px 16px;"
            "  border-radius: 4px;"
            "  font-size: 16px;"
            "}"
            "QPushButton:hover {"
            "  background-color: #3e7321;"
            "}"
        );

        // 显示对话框
        if (dialog.exec() == QDialog::Accepted) {
            // 获取新值
            bool ok;
            double newValue = QLocale().toDouble(valueEdit->text(),&ok);

            if (ok) {
                // 调用 setConstantValue 函数，传递所有当前值
                // 注意：这里使用新值替换当前值
                if (title.contains("CO₂")) {
                    clt->setConstantValue(farmId,newValue, tempValue, humidityValue, lightValue);
                } else if (title.contains("温度")) {
                    clt->setConstantValue(farmId,co2Value, newValue, humidityValue, lightValue);
                } else if (title.contains("湿度")) {
                    clt->setConstantValue(farmId,co2Value, tempValue, newValue, lightValue);
                } else if (title.contains("光照")) {
                    clt->setConstantValue(farmId,co2Value, tempValue, humidityValue, newValue);
                }

                qDebug() << "设置新值:" << newValue;
            } else {
                QMessageBox::warning(this, "输入错误", "请输入有效的数字");
            }
        }


            //clt->setConstantValue(1,1.2,30,20,1000);
            //qDebug()<<newValue;
            // 更新值
            //value = newValue;

            // 更新显示
            //updateDataDisplay();


}
void FarmInfoWidget::setFarmId(int farmId)
{
    this->farmId = farmId;
    loadData(); // 加载新农场的数据
}
void FarmInfoWidget::onCo2Clicked()
{
    editValue("编辑CO₂浓度", "ppm", co2Value);
   // qDebug()<<co2Value;


}

void FarmInfoWidget::onTempClicked()
{
    editValue("编辑温度", "°C", tempValue);
}

void FarmInfoWidget::onHumidityClicked()
{
    editValue("编辑湿度", "%", humidityValue);
}

void FarmInfoWidget::onLightClicked()
{
    editValue("编辑光照强度", "lux", lightValue);
}
